import { Request, Response } from 'express'
import { UserModel } from '../models/user.model'
import { comparePassword, generateToken, hashPassword } from '../utils/auth'
import { ApiResponse } from '../types'
import { ErrorCode, ErrorResponse } from '../types/error'
import { RowDataPacket } from 'mysql2'
import { pool } from '../database/db'

export class AuthController {
  async login(req: Request, res: Response) {
    try {
      const { username, password } = req.body

      // 验证请求数据
      if (!username || !password) {
        return res.status(ErrorCode.BAD_REQUEST).json({
          status: 'error',
          code: ErrorCode.BAD_REQUEST,
          message: '用户名和密码不能为空'
        } as ErrorResponse)
      }

      // 查找用户
      const user = await UserModel.findByUsername(username)
      if (!user) {
        return res.status(ErrorCode.UNAUTHORIZED).json({
          status: 'error',
          code: ErrorCode.UNAUTHORIZED,
          message: '用户名或密码错误'
        } as ErrorResponse)
      }

      // 验证密码
      const isValidPassword = await comparePassword(password, user.password)
      console.log(password)
      console.log(user.password)
      if (!isValidPassword) {
        return res.status(ErrorCode.UNAUTHORIZED).json({
          status: 'error',
          code: ErrorCode.UNAUTHORIZED,
          message: '用户名或密码错误'
        } as ErrorResponse)
      }

      // 检查用户状态
      if (user.status !== 1) {
        return res.status(ErrorCode.FORBIDDEN).json({
          status: 'error',
          code: ErrorCode.FORBIDDEN,
          message: '账号已被禁用'
        } as ErrorResponse)
      }

      // 生成 token
      const token = generateToken({
        id: user.id,
        username: user.username,
        role: user.role
      })

      // 返回用户信息和 token
      res.json({
        status: 'success',
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            nickname: user.nickname,
            avatar: user.avatar,
            role: user.role
          }
        }
      } as ApiResponse)
    } catch (error) {
      console.error('Login error:', error)
      return res.status(ErrorCode.INTERNAL_ERROR).json({
        status: 'error',
        code: ErrorCode.INTERNAL_ERROR,
        message: '服务器错误'
      } as ErrorResponse)
    }
  }

  async register(req: Request, res: Response) {
    try {
      const { username, password, nickname } = req.body

      // 验证请求数据
      if (!username || !password || !nickname) {
        return res.status(ErrorCode.BAD_REQUEST).json({
          status: 'error',
          code: ErrorCode.BAD_REQUEST,
          message: '用户名、密码和昵称不能为空'
        } as ErrorResponse)
      }

      // 检查用户名是否已存在
      const existingUser = await UserModel.findByUsername(username)
      if (existingUser) {
        return res.status(ErrorCode.CONFLICT).json({
          status: 'error',
          code: ErrorCode.CONFLICT,
          message: '用户名已存在'
        } as ErrorResponse)
      }

      // 加密密码
      const hashedPassword = await hashPassword(password)
      console.log(hashedPassword)
      // 创建用户
      const result = await UserModel.create({
        username,
        password: hashedPassword,
        nickname,
        role: 'user'  // 默认角色
      })

      res.status(201).json({
        status: 'success',
        message: '注册成功',
        data: {
          username,
          nickname
        }
      } as ApiResponse)
    } catch (error) {
      console.error('Register error:', error)
      return res.status(ErrorCode.INTERNAL_ERROR).json({
        status: 'error',
        code: ErrorCode.INTERNAL_ERROR,
        message: '服务器错误',
        details: process.env.NODE_ENV === 'development' ? error : undefined
      } as ErrorResponse)
    }
  }

  // 获取用户信息
  async getProfile(req: Request, res: Response) {
    try {
      const userId = req.user?.id
      if (!userId) {
        return res.status(401).json({
          status: 'error',
          message: '未授权'
        } as ApiResponse)
      }

      const [user] = await pool.execute<RowDataPacket[]>(
        'SELECT id, username, role, avatar FROM users WHERE id = ?',
        [userId]
      )

      if (!user[0]) {
        return res.status(404).json({
          status: 'error',
          message: '用户不存在'
        } as ApiResponse)
      }

      res.json({
        status: 'success',
        data: {
          id: user[0].id,
          username: user[0].username,
          role: user[0].role,
          avatar: user[0].avatar
        }
      } as ApiResponse)
    } catch (error) {
      console.error('Get profile error:', error)
      res.status(500).json({
        status: 'error',
        message: '服务器错误'
      } as ApiResponse)
    }
  }
} 